package org.kaer.election.utils;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

public class UdpSearchHelper extends AsyncTask<String, Integer, String> {
	private int port; // 监听端口号
	private String BROADCAST_IP = "224.0.0.1";
	private Context mContext;
	private WifiManager.MulticastLock lock;

	public UdpSearchHelper(Context mContext, int port) {
		// TODO Auto-generated constructor stub
		this.port = port;
		this.mContext = mContext;
		WifiManager manager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
		lock = manager.createMulticastLock("udp");
	}

	@Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
		System.out.println("搜索周边");
		lock.acquire();
	}

	@Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		try {
			MulticastSocket multicastSocket = new MulticastSocket(port);
			InetAddress serverAddress = InetAddress.getByName(BROADCAST_IP);
			System.out.println(serverAddress.isMulticastAddress());
			multicastSocket.joinGroup(serverAddress);

			byte data[] = new byte[1024];

			DatagramPacket pack = new DatagramPacket(data, data.length, serverAddress, port);
			System.out.println("before receive");
			multicastSocket.setLoopbackMode(true);
			multicastSocket.setSoTimeout(0);
			multicastSocket.receive(pack);
			System.out.println("after receive");
			String serverIP = new String(pack.getData(), pack.getOffset(), pack.getLength());
//			multicastSocket.leaveGroup(serverAddress);
//			multicastSocket.close();
			return serverIP;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		System.out.println("ip = " + result);
		lock.release();
	}
}
